import { userStore } from "@/stores/user";
import { messageCof } from "./message";
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";
import { ElMessage } from "element-plus";
import { showMessage } from "./status";
import router from "@/router";
let request: AxiosInstance = axios.create({
  headers: {
    Accept: "appliction/json",
    "Content-Type": "application/json;charset=UTF-8",
  },
  // 请求时长
  timeout: 1000 * 30,
  // 请求的base地址 TODO:这块以后根据不同的模块调不同的api
  baseURL: import.meta.env.VITE_RES_URL,
});

request.interceptors.request.use(
  (config: any) => {
    const store = userStore();
    console.log(store.token);

    config.headers.Authorization = `Bearer ${store.token}`;
    return config;
  },
  // 请求失败
  (error: any) => {
    return Promise.reject(error);
  }
);
// 响应拦截器
request.interceptors.response.use(
  function (response: AxiosResponse) {
    console.log(response);
    if (response.headers.authorization) {
      localStorage.setItem("app_token", response.headers.authorization);
    } else {
      if (response.data && response.data.token) {
        localStorage.setItem("app_token", response.data.token);
      }
    }
    if (response.data.code == 403) {
      localStorage.clear();
      router.replace("/");
    }
    if (response.data.status == 200) {
      return response;
    } else {
      const message = showMessage(Number(response.data.status));
      messageCof(message, "error");
      return response;
    }
  },
  function (error) {
    const { response } = error;
    if (response) {
      // 请求已发出，但是不在2xx的范围
      const message = showMessage(response.status);
      ElMessage.warning(message);
      return Promise.reject(response.data);
    } else {
      ElMessage.warning("网络连接异常,请稍后再试!");
    }
  }
);
// 只需要考虑单一职责，这块只封装axios
export default request;
